const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');

/**
 * 搜索日记
 * GET /api/search/diaries
 */
router.get('/diaries', authenticateToken, async (req, res) => {
  try {
    const {
      keyword = '',
      page = 1,
      limit = 10,
      categoryId,
      tagIds,
      startDate,
      endDate
    } = req.query;

    const user_id = req.user.id;
    const offset = (page - 1) * limit;

    // 构建查询条件
    const where = { user_id };

    // 关键词搜索
    if (keyword.trim()) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 分类筛选
    if (categoryId) {
      where.category_id = categoryId;
    }

    // 日期范围筛选
    if (startDate && endDate) {
      where.diary_date = {
        [Op.between]: [startDate, endDate]
      };
    } else if (startDate) {
      where.diary_date = {
        [Op.gte]: startDate
      };
    } else if (endDate) {
      where.diary_date = {
        [Op.lte]: endDate
      };
    }

    // 构建包含关系
    const include = [
      {
        model: db.Category,
        as: 'category',
        attributes: ['id', 'name', 'color', 'icon']
      },
      {
        model: db.Tag,
        as: 'tags',
        attributes: ['id', 'name', 'color'],
        through: { attributes: [] }
      }
    ];

    // 标签筛选
    if (tagIds && tagIds.length > 0) {
      const tagIdArray = Array.isArray(tagIds) ? tagIds : [tagIds];
      include.push({
        model: db.Tag,
        as: 'filterTags',
        where: { id: { [Op.in]: tagIdArray } },
        attributes: [],
        through: { attributes: [] }
      });
    }

    const { count, rows } = await db.Diary.findAndCountAll({
      where,
      include,
      offset,
      limit: parseInt(limit),
      order: [['diary_date', 'DESC']],
      distinct: true
    });

    // 高亮关键词
    const highlightedRows = rows.map(diary => {
      const diaryData = diary.toJSON();
      if (keyword.trim()) {
        const regex = new RegExp(`(${keyword})`, 'gi');
        diaryData.title = diaryData.title.replace(regex, '<mark>$1</mark>');
        // 截取内容片段
        const contentText = diaryData.content.replace(/<[^>]*>/g, '');
        const keywordIndex = contentText.toLowerCase().indexOf(keyword.toLowerCase());
        if (keywordIndex !== -1) {
          const start = Math.max(0, keywordIndex - 50);
          const end = Math.min(contentText.length, keywordIndex + keyword.length + 50);
          diaryData.contentSnippet = '...' + contentText.substring(start, end) + '...';
          diaryData.contentSnippet = diaryData.contentSnippet.replace(regex, '<mark>$1</mark>');
        } else {
          diaryData.contentSnippet = contentText.substring(0, 100) + '...';
        }
      }
      return diaryData;
    });

    res.json({
      success: true,
      data: {
        results: highlightedRows,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: count,
          totalPages: Math.ceil(count / limit)
        }
      }
    });

  } catch (error) {
    console.error('搜索日记错误:', error);
    res.status(500).json({
      error: '搜索失败'
    });
  }
});

/**
 * 获取搜索建议
 * GET /api/search/suggestions
 */
router.get('/suggestions', authenticateToken, async (req, res) => {
  try {
    const { keyword = '' } = req.query;
    const user_id = req.user.id;

    if (!keyword.trim()) {
      return res.json({
        success: true,
        data: []
      });
    }

    // 搜索匹配的日记标题
    const titleSuggestions = await db.Diary.findAll({
      where: {
        user_id,
        title: { [Op.like]: `%${keyword}%` }
      },
      attributes: ['title'],
      limit: 5,
      group: ['title']
    });

    // 搜索匹配的标签
    const tagSuggestions = await db.Tag.findAll({
      where: {
        user_id,
        name: { [Op.like]: `%${keyword}%` }
      },
      attributes: ['name'],
      limit: 5
    });

    // 搜索匹配的分类
    const categorySuggestions = await db.Category.findAll({
      where: {
        user_id,
        name: { [Op.like]: `%${keyword}%` }
      },
      attributes: ['name'],
      limit: 3
    });

    const suggestions = [
      ...titleSuggestions.map(item => ({ type: 'title', value: item.title })),
      ...tagSuggestions.map(item => ({ type: 'tag', value: item.name })),
      ...categorySuggestions.map(item => ({ type: 'category', value: item.name }))
    ];

    res.json({
      success: true,
      data: suggestions.slice(0, 10) // 最多返回10个建议
    });

  } catch (error) {
    console.error('获取搜索建议错误:', error);
    res.status(500).json({
      error: '获取搜索建议失败'
    });
  }
});

/**
 * 获取热门搜索关键词
 * GET /api/search/hot-keywords
 */
router.get('/hot-keywords', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    // 获取用户最常用的标签作为热门关键词
    const hotTags = await db.Tag.findAll({
      where: { user_id },
      attributes: [
        'name',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'usage_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          through: { attributes: [] }
        }
      ],
      group: ['Tag.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: 8
    });

    // 获取最常用的分类名称
    const hotCategories = await db.Category.findAll({
      where: { user_id },
      attributes: [
        'name',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'usage_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: []
        }
      ],
      group: ['Category.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: 4
    });

    const hotKeywords = [
      ...hotTags.map(tag => tag.name),
      ...hotCategories.map(category => category.name)
    ].slice(0, 10);

    res.json({
      success: true,
      data: hotKeywords
    });

  } catch (error) {
    console.error('获取热门关键词错误:', error);
    res.status(500).json({
      error: '获取热门关键词失败'
    });
  }
});

module.exports = router; 